<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Session;

/**
 * 会员接口
 */
class Activity extends Api
{
    protected $noNeedLogin = ['getDetail','createActivityOrder','payActivity','wxxmlactivity','rebackMoney','makePoster','testimg','testrec','testdbx','rePoster'];
    protected $noNeedRight = '*';
    protected $hid = null;
    protected $adminId = null;

    public function _initialize()
    {
        parent::_initialize();
    }

    public function testdbx(){
        $background = ROOT_PATH.'/public/qrcode.jpg';
        generateImg ( $background,'原价 ￥300','￥250');
    }
    public function testrec(){

        $imgpath = ROOT_PATH.'/public/poster/test5.jpg';
        $imgpath2 = ROOT_PATH.'/public/poster/test55.jpg';
        $imgg = radius_img($imgpath);

        imagepng($imgg,$imgpath2);

        imagedestroy($imgg);


    }
    public function testimg(){


        $imgpath = ROOT_PATH.'/public/poster/header.jpg';
        $imgpath2 = ROOT_PATH.'/public/poster/test.jpg';
        $imgg = yuan_img($imgpath);
        imagepng($imgg,$imgpath2);
        imagedestroy($imgg);
        print_r($imgg);die;

    }

    //生成海报
    public function makePoster(){
        $filename = ROOT_PATH.'/public/qrcode.jpg';
        $username = "@路上绍伟";
        $userheader = ROOT_PATH.'/public/poster/test.jpg';
        $text1 = "建的云漫松件|688元抢樱飞/凤舞/修竹/杏会2天";
        $text2 = "1晚。应季采摘+双人早餐+趣味体验。";
        $bgimg = ROOT_PATH.'/public/poster/posterbg.jpg';
        $bgactimg = ROOT_PATH.'/public/poster/test55.jpg';
        $ermurl = ROOT_PATH.'/public/poster/qrcode.png';
        $fonttff = ROOT_PATH.'/public/poster/simhei.ttf';
        $remark = "★我发现这个东西还不错呢";

        $config = array(
            'text'=>array(
                array(
                    'text'=>$username,
                    'left'=>140,
                    'top'=>110,
                    'fontPath'=>$fonttff,    //字体文件
                    'fontSize'=>24,             //字号
                    'fontColor'=>'71,61,2',       //字体颜色
                    'angle'=>0,
                ),
                array(
                    'text'=>$remark,
                    'left'=>140,
                    'top'=>160,
                    'fontPath'=>$fonttff,    //字体文件
                    'fontSize'=>24,             //字号
                    'fontColor'=>'71,61,2',       //字体颜色
                    'angle'=>0,
                ),
                array(
                    'text'=>$text1,
                    'left'=>50,
                    'top'=>-330,
                    'fontPath'=>$fonttff,    //字体文件
                    'fontSize'=>24,             //字号
                    'fontColor'=>'83,83,83',       //字体颜色
                    'angle'=>0,
                ),
                array(
                    'text'=>$text2,
                    'left'=>50,
                    'top'=>-280,
                    'fontPath'=>$fonttff,    //字体文件
                    'fontSize'=>24,             //字号
                    'fontColor'=>'83,83,83',       //字体颜色
                    'angle'=>0,
                )
            ),
            'image'=>array(

                array(
                    'url'=>$userheader, //头像
                    'left'=>45,
                    'top'=>85,
                    'right'=>0,
                    'stream'=>0,
                    'bottom'=>0,
                    'width'=>80,
                    'height'=>80,
                    'opacity'=>100,
                ),
                array(
                    'url'=>$bgactimg, //头像
                    'left'=>49,
                    'top'=>240,
                    'right'=>0,
                    'stream'=>0,
                    'bottom'=>0,
                    'width'=>651,
                    'height'=>700,
                    'opacity'=>100,
                ),
                array(
                    'url'=>$ermurl, //图片资源路径 二维码
                    'left'=>530,
                    'top'=>-60,
                    'stream'=>0,             //图片资源是否是字符串图像流
                    'right'=>0,
                    'bottom'=>0,
                    'width'=>150,
                    'height'=>150,
                    'opacity'=>100
                ),
            ),
            'background'=>$bgimg,
        );

        echo createPoster($config,$filename);

    }




    //返回海报图片
    public function rePoster(){
        $uid = $this->request->request("uid");
        $aid = $this->request->request("aid");

        if(empty($uid)){
            $this->error("用户参数错误");
        }
        if(empty($aid)){
            $this->error("活动参数错误");
        }

        //获取用户头像
        $userinfo = db("user")->where(['id'=>$uid])->field("nickName,yuanavatarUrl")->find();
        //获取活动信息
        $actinfo = db("activity")->where(['id'=>$aid])->field("fx_posterone")->find();
        $fonttff = ROOT_PATH.'public/poster/simhei.ttf';
        $filename = "poster_".$aid."_".$uid ."_".time().".jpg";
        $filename2 = ROOT_PATH.'public/uploads/poster/'.$filename;
        //获取域名
        $host = "https://".$_SERVER['HTTP_HOST'];
        $filename2_2 = $host.'/uploads/poster/'.$filename;
        $username = "@".$userinfo['nickName'];
        $userheader = ROOT_PATH.'public'.$userinfo['yuanavatarUrl'];
        $background = ROOT_PATH.'public'.$actinfo['fx_posterone'];



        $config = array(
            'text'=>array(
                array(
                    'text'=>$username,
                    'left'=>140,
                    'top'=>110,
                    'fontPath'=>$fonttff,    //字体文件
                    'fontSize'=>24,             //字号
                    'fontColor'=>'71,61,2',       //字体颜色
                    'angle'=>0,
                )
            ),
            'image'=>array(

                array(
                    'url'=>$userheader, //头像
                    'left'=>45,
                    'top'=>85,
                    'right'=>0,
                    'stream'=>0,
                    'bottom'=>0,
                    'width'=>80,
                    'height'=>80,
                    'opacity'=>100,
                )
            ),
            'background'=>$background
        );



        //生成最终海报
        createPoster($config,$filename2);

        if(file_exists($filename2))
        {
            $this->success("success",$filename2_2);
        }
        else
        {
            $this->error("海报生成失败");
        }

    }

    //活动详情
    public function getDetail(){
        $aid = $this->request->request("aid");
        if(empty($aid)){
            $this->error("参数错误");
        }

        $info = db("activity")->where(['id'=>$aid])->find();
        if($info){
            $host = "http://".$_SERVER['HTTP_HOST'];
            $imgsarr = $imgsarr2 = [];

            //轮播图片
            if($info['imgs']){
                $imgsarr = explode(',',$info['imgs']);
                foreach ($imgsarr as &$v){
                    $v = $host.$v;
                }
            }

            //详情图片
            $detimgs = [];
            if($info['detailimgs']){
                $imgsarr2 = explode(',',$info['detailimgs']);
                foreach ($imgsarr2 as $k=>$v){
                    $v = $host.$v;
                    //动态计算高度 暂时不考虑 固定长度 720*2500
                    /*  $img = imagecreatefromstring(file_get_contents($v));
                      $imgheight = imagesy($img);*/
                    $detimgs[$k]['imgurl'] = $v;
                    $detimgs[$k]['imgheight'] = 2500;

                }
            }
            $info['img'] = $host.$info['img'];
            $info['fx_ewm'] = $host.$info['fx_ewm'];
            $info['imgs'] = $imgsarr;
            $info['detailimgs'] = $detimgs;
            $this->success("success",$info);
        }else{
            $this->error("数据错误");
        }

    }

    //创建活动订单

    public function createActivityOrder(){


        $aid = $this->request->request("aid");
        $uid = $this->request->request("uid");

        if(empty($aid) || empty($uid)){
            $this->error("用户参数错误");
        }
        $userinfo = db("user")->where(['id'=>$uid])->find();
        $openid = $userinfo['openid'];

        //判断用户是否多次支付 （对同一个订单支付多次支付）
        $two['aid'] = $aid;
        $two['user_id'] = $uid;
        $two['pay_status'] = 0;
        $oldorder = db("orderactivity")->where($two)->find();
        if($oldorder){
            //获取支付数据
            $payres = $this->payActivity($openid,$oldorder['order_number'],$oldorder['price']);

            if($payres['code'] = 1){
                $this->success("success",$payres['data']);
            }else{
                $this->error($payres['data']);
            }


        }else{

            //获取订单金额数据
            $info = db("activity")->where("id = $aid")->find();
            if(!$info){
                $this->error("活动数据错误");
            }
            try{
                $time = time();

                $orderData["order_number"] = date("YmdHis", time()) . rand(10000000, 99999999);
                $orderData["user_id"] = $uid;
                $orderData["aid"] = $aid;
                $orderData["price"] = $info["price"];
                $orderData["income"] = $info["price"];
                $orderData["preprice"] = $info["preprice"];
                $orderData["hotelname"] = $info["hotelname"];
                $orderData["title"] = $info["title"];
                $orderData["a_phone"] = $info["phone"];
                $orderData["user_phone"] = $userinfo["phone"];
                $orderData["order_phone"] = $userinfo["phone"];
                $orderData["order_name"] = $userinfo["nickName"];
                $orderData["add_time"] = $time;
                $orderData["pay_time"] = $time;
                $orderData["payend_time"] = $time + 30*60;
                $orderData["pay_status"] = 0;
                $orderData["activity_html"] = json_encode($info);

                if(db('orderactivity')->insert($orderData)){
                    //获取支付数据
                    $payres = $this->payActivity($openid,$orderData["order_number"],$info["price"]);

                    if($payres['code'] = 1){
                        $this->success("success",$payres['data']);
                    }else{
                        $this->error($payres['data']);
                    }

                }else{
                    $this->error("订单生成失败");
                }

            }catch (\think\exception\PDOException $e){
                $this->error($e->getMessage());
            }

        }

    }



    //支付
    public function payActivity($openid,$ordernumber,$price){
        $res['code'] = 0;
        $res['data'] = [];
        if(!$openid || !$ordernumber || !$price){
            $res['data'] = "订单参数错误";
            return $res;
        }
        $price= $price * 100;  //真实需要支付的金额
        $out_trade_no = $ordernumber;
        $PrePay = WxPay::PrePayActivity($out_trade_no,$openid,$price);  //统一下单

        if($PrePay["return_code"]=="FAIL"){
            $res['data'] = "支付状态错误";
            return $res;
        }else{
            if(empty($PrePay["prepay_id"])){
                $res['data'] = "支付参数prepay_id错误";
                return $res;
            }else{
                $PrePayId=$PrePay["prepay_id"];  // 获取预支付id
                $PaySign=WxPay::getPaySign($PrePayId,$PrePay["nonce_str"]);
                $a= array("prepay_id"=>$PrePayId,"paySign"=>$PaySign["PaySign"],"nonce_str"=>$PrePay["nonce_str"],"timeStamp"=>$PaySign["timeStamp"],"order_no"=>$out_trade_no);
                $res['code'] = 1;
                $res['data'] = $a;
                return $res;
            }

        }
    }

    //活动支付回调
    public function wxxmlactivity(){
        $activityxml = file_get_contents("php://input");


        file_put_contents("testctivity.json",var_export($activityxml,true).PHP_EOL,FILE_APPEND);

        //将xml转化为json格式
        $jsonxml = json_encode(simplexml_load_string($activityxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        //转成数组
        $result = json_decode($jsonxml, true);
        if($result){
            //如果成功返回了
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                //写入回调日志
                file_put_contents("wxxmlactivity.json",var_export($result,true).PHP_EOL,FILE_APPEND);

                $ordernumber = $result['out_trade_no'];
                $up['pay_status'] = 1;
                $up['upd_time'] = 1;
                $up['pay_time'] = time();
                db("orderactivity")->where(['order_number'=>$ordernumber])->update($up);
            }
        }



    }

    //退款接口
    public function rebackMoney(){

        $all_money = $this->request->request("all_money");
        $out_trade_no = $this->request->request("out_trade_no");
        $return_money = $this->request->request("return_money");
        $refund_number = $this->request->request("refund_number");
        $transaction_id = $this->request->request("transaction_id");


        //通过微信api进行退款流程
        $nonce_str = WxPay::str_rand();//随机32位字符串
        $total_fee = $all_money * 100;//总金额，单位：分
        $refund_fee = $return_money * 100;//退款金额，单位：分



        $parma = array(
            'appid'=> WxPay::appid,
            'mch_id'=> WxPay::mch_id,
            'nonce_str'=> $nonce_str,
            'out_trade_no'=> $out_trade_no,//小程序自定义订单号，支付时后台生成
            'out_refund_no'=> $refund_number,
            'total_fee'=> $total_fee,
            'refund_fee'=> $refund_fee,
            'transaction_id' => $transaction_id,//小程序平台订单号，微信平台生成
        );

        $KEY = WxPay::key;//小程序支付秘钥
        $parma['sign'] = $this->getSign($parma, $KEY);

        $post_xml = $this->arrayToXml($parma);//把参数转化成xml格式

        //向微信平台api发送退款参数
        $xmlresult = $this->postXmlSSLCurl($post_xml,'https://api.mch.weixin.qq.com/secapi/pay/refund');

        //解析返回的参数
        $array = $this->xml2array($xmlresult);
        print_r($array);die;

    }

    protected function getSign($params, $key)
    {
        ksort($params, SORT_STRING);
        $unSignParaString = $this->formatQueryParaMap($params, false);
        return $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
    }

    protected function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    //数组转字符串方法
    protected function arrayToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {

            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    //获取xml里面数据，转换成array
    private function xml2array($xml)
    {
        $p = xml_parser_create();
        xml_parse_into_struct($p, $xml, $vals, $index);
        xml_parser_free($p);
        $data = [];

        foreach ($index as $key => $value) {
            if ($key == 'xml' || $key == 'XML') continue;
            $tag = $vals[$value[0]]['tag'];
            $value = $vals[$value[0]]['value'];
            $data[$tag] = $value;
        }
        return $data;
    }


    //需要使用证书的请求
    function postXmlSSLCurl($xml,$url,$second=30)
    {
        //使用的啊里云宝塔，存放证书路径，放在public中，新建cert

        $cert = '/www/wwwroot/minsuceshi/public/cert/apiclient_cert.pem';
        $key = '/www/wwwroot/minsuceshi/public/cert/apiclient_key.pem';
        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //设置证书
        //使用证书：cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释,使用getcwd()方法，拼接证书的绝对路径
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT,$cert);

        //默认格式为PEM，可以注释,使用getcwd()方法，拼接证书的绝对路径
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY,$key);

        //post提交方式
        curl_setopt($ch, CURLOPT_POST, true);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);

        $data = curl_exec($ch);

//        p($data);die;
        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error" . "<br>";
            curl_close($ch);
            return false;
        }
    }





}
